#include <iostream>
#include <string>
#include <unistd.h>
#include "Comm.hpp"
#include "Logger.hpp"
#include "InetAddr.hpp"
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

void Usage(std::string proc)
{
    std::cerr << "Usage: " << proc << " serverip serverport" << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    std::string severip = argv[1];
    uint16_t severport = std::stoi(argv[2]);

    // 创建客户端套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        LOG(LogLevel::ERROR) << "create socket error!";
        exit(SOCKET_CREATE_ERR);
    }
    // connet 向服务器发起请求
    InetAddr sever(severport, severip);
    if (connect(sockfd, sever.Addr(), sever.Length()) != 0)
    {
        LOG(LogLevel::ERROR) << "sockfd connect error!";
        exit(SOCKET_CONNECT_ERR);
    }
    std::cout << "connect " << sever.ToString() << " success" << std::endl;
    // 写入数据
    while (true)
    {
        std::cout << "please enter@ ";
        std::string line;
        std::getline(std::cin, line);

        ssize_t n = write(sockfd, line.c_str(), line.size());
        if(n >= 0)
        {
            char buffer[1024];
            ssize_t m = read(sockfd, &buffer, sizeof(buffer) - 1);
            if(m > 0)
            {
                buffer[m] = 0;
                std::cout << buffer << std::endl;
            }
        }
    }

    return 0;
}